package com.swx.identityservice.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * /**
 * * 上传图片到服务器
 * * @param webPath  服务器处理地址
 * * @param uploadFilePath  上传文件地址
 * * @return
 */

@Slf4j
//@PropertySource(value = {"classpath:application.yml"},encoding="utf-8")
@RestController
public class UploadUtils {
//
//    @Value("${file.imagePath}")
//    private String imagePath;
//

    public static List<String> UploadImg(List<MultipartFile> portrait) {
        List<String> fileurl = new ArrayList<>();
        String uploaddir = "";
        try {
            if (portrait.size() > 0) {
                uploaddir = "c:/upload/2018-05-20/";
                File dir = new File(uploaddir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                for (MultipartFile file : portrait) {
                    if (!file.isEmpty()) {
                        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//拿到后缀
                        log.info("suffix===" + suffix);
                        String filename = String.format("%s%s", UUID.randomUUID().toString(), suffix);
                        log.info("filename==" + filename);
                        File fileinfo = new File(String.format("%s%s", uploaddir, filename));
                        FileUtils.writeByteArrayToFile(fileinfo, file.getBytes());
                        String url = String.format("/2018-05-20/%s", filename);
                        log.info("url===" + url);
                        fileurl.add(url);
                    }
                }
            }
            // fileurl 图片地址清单
        } catch (IOException e) {

        }
        return fileurl;
    }


    public static String Upload(MultipartFile file) {
        String url = "";
        try {
            if (file.getSize() > 0) {
                String uploaddir = "c:/upload/2018-05-20/";
                File dir = new File(uploaddir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                if (!file.isEmpty()) {
                    String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));//后缀
                    String filename = String.format("%s%s", UUID.randomUUID().toString(), suffix);
                    File fileinfo = new File(String.format("%s%s", uploaddir, filename));
                    FileUtils.writeByteArrayToFile(fileinfo, file.getBytes());
                    url = String.format("/2018-05-20/%s", filename);
                }
            }
            // url 图片地址清单
        } catch (IOException e) {

        }
        return url;
    }
}
